package org.framework.lazy.cloud.network.heartbeat.server.standalone.application.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyPermeateVisitorContext;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelFlowAdapter;
import org.framework.lazy.cloud.network.heartbeat.server.netty.socket.NettyServerPermeateServerConnectVisitorSocket;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyInternalNetworkServerPermeateMappingApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.LazyInternalNetworkServerPermeateServerMappingDTOAssembler;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.lazy.netty.server.permeate.server.mapping.*;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.dto.LazyInternalNetworkServerPermeateMappingDTO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.permeate.server.mapping.LazyInternalNetworkServerPermeateServerMapping;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.permeate.server.mapping.LazyInternalNetworkServerPermeateServerMappingRepository;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.database.lazy.web.plus.stereotype.LazyApplication;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe 服务端网络渗透映射
 *
 * @author Jia wei Wu
 * @date 2024/09/17 01:35 下午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyApplicationImpl
 **/
@Slf4j
@LazyApplication
public class LazyInternalNetworkServerPermeateMappingApplicationImpl implements LazyInternalNetworkServerPermeateMappingApplication {

    @Resource
    LazyInternalNetworkServerPermeateServerMappingRepository lazyInternalNetworkServerPermeateServerMappingRepository;

    @Resource
    ServerNodeProperties serverNodeProperties;

    @Resource
    ChannelFlowAdapter channelFlowAdapter;

    /**
     * describe 新增服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingStoryCommand 新增服务端网络渗透映射
     * @return {@link Result< LazyInternalNetworkServerPermeateServerMapping >} 服务端网络渗透映射新增后领域对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateServerMapping> story(LazyInternalNetworkServerPermeateServerMappingStoryCommand lazyInternalNetworkServerPermeateServerMappingStoryCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingStoryCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyInternalNetworkServerPermeateServerMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetPort();
        Integer visitorPort = lazyInternalNetworkServerPermeateServerMapping.getVisitorPort();
        Boolean isSsl = lazyInternalNetworkServerPermeateServerMapping.getIsSsl();
        this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        return lazyInternalNetworkServerPermeateServerMappingRepository.story(lazyInternalNetworkServerPermeateServerMapping);
    }

    /**
     * describe 批量新增服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingStoryCommandList 批量新增服务端网络渗透映射
     * @return {@link Result<List< LazyInternalNetworkServerPermeateServerMapping >>} 服务端网络渗透映射新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<List<LazyInternalNetworkServerPermeateServerMapping>> batchStory(List<LazyInternalNetworkServerPermeateServerMappingStoryCommand> lazyInternalNetworkServerPermeateServerMappingStoryCommandList) {
        List<LazyInternalNetworkServerPermeateServerMapping> lazyInternalNetworkServerPermeateServerMappingList = lazyInternalNetworkServerPermeateServerMappingStoryCommandList.stream().map(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::toLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList());
        for (LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping : lazyInternalNetworkServerPermeateServerMappingList) {
            String serverId = serverNodeProperties.getNodeId();
            lazyInternalNetworkServerPermeateServerMapping.setServerId(serverId);
            // 开启端口
            String permeateTargetIp = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetIp();
            Integer permeateTargetPort = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetPort();
            Integer visitorPort = lazyInternalNetworkServerPermeateServerMapping.getVisitorPort();
            Boolean isSsl = lazyInternalNetworkServerPermeateServerMapping.getIsSsl();
            this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        }
        return lazyInternalNetworkServerPermeateServerMappingRepository.batchStory(lazyInternalNetworkServerPermeateServerMappingList);
    }

    /**
     * describe 更新服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingUpdateCommand 更新服务端网络渗透映射
     * @return {@link Result< LazyInternalNetworkServerPermeateServerMapping >} 服务端网络渗透映射领域对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateServerMapping> updateOne(LazyInternalNetworkServerPermeateServerMappingUpdateCommand lazyInternalNetworkServerPermeateServerMappingUpdateCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingUpdateCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyInternalNetworkServerPermeateServerMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyInternalNetworkServerPermeateServerMapping.getPermeateTargetPort();
        Integer visitorPort = lazyInternalNetworkServerPermeateServerMapping.getVisitorPort();
        Boolean isSsl = lazyInternalNetworkServerPermeateServerMapping.getIsSsl();
        this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        return lazyInternalNetworkServerPermeateServerMappingRepository.story(lazyInternalNetworkServerPermeateServerMapping);
    }

    /**
     * describe 查询单个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingQueryOneCommand 查询单个服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMappingDTO>} 服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMappingDTO> findOne(LazyInternalNetworkServerPermeateServerMappingQueryOneCommand lazyInternalNetworkServerPermeateServerMappingQueryOneCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryOneCommand);
        return lazyInternalNetworkServerPermeateServerMappingRepository.findOne(lazyInternalNetworkServerPermeateServerMapping).convert(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping);
    }

    /**
     * describe 查询多个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingQueryListCommand 查询多个服务端网络渗透映射
     * @return {@link Result<List<LazyInternalNetworkServerPermeateMappingDTO>>} 服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<List<LazyInternalNetworkServerPermeateMappingDTO>> findList(LazyInternalNetworkServerPermeateServerMappingQueryListCommand lazyInternalNetworkServerPermeateServerMappingQueryListCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryListCommand);
        return lazyInternalNetworkServerPermeateServerMappingRepository.findList(lazyInternalNetworkServerPermeateServerMapping).convert(lazyInternalNetworkServerPermeateMappings -> lazyInternalNetworkServerPermeateMappings.stream().map(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList()));
    }

    /**
     * describe 分页查询多个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingQueryListCommand 分页查询多个服务端网络渗透映射
     * @return {@link Result<LazyPage<LazyInternalNetworkServerPermeateMappingDTO>>} 分页服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyPage<LazyInternalNetworkServerPermeateMappingDTO>> findPage(int size, int current, LazyInternalNetworkServerPermeateServerMappingQueryListCommand lazyInternalNetworkServerPermeateServerMappingQueryListCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryListCommand);
        return lazyInternalNetworkServerPermeateServerMappingRepository.findPage(size, current, lazyInternalNetworkServerPermeateServerMapping).convert(page -> page.convert(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping));
    }

    /**
     * describe 删除服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingRemoveCommand 删除服务端网络渗透映射
     * @return {@link Result< LazyInternalNetworkServerPermeateServerMapping >} 服务端网络渗透映射
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateServerMapping> remove(LazyInternalNetworkServerPermeateServerMappingRemoveCommand lazyInternalNetworkServerPermeateServerMappingRemoveCommand) {
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingRemoveCommand);
        // 开启端口
        Integer visitorPort = lazyInternalNetworkServerPermeateServerMapping.getVisitorPort();
        this.closePermeateSocket(visitorPort);
        return lazyInternalNetworkServerPermeateServerMappingRepository.remove(lazyInternalNetworkServerPermeateServerMapping);
    }

    /**
     * 初始化 网络渗透socket
     *
     * @return
     */
    @Override
    public Result<?> initPermeateSocket() {
        // 查询所有的服务端渗透配置
        LazyInternalNetworkServerPermeateServerMapping lazyInternalNetworkServerPermeateServerMapping = new LazyInternalNetworkServerPermeateServerMapping();
        return lazyInternalNetworkServerPermeateServerMappingRepository.findList(lazyInternalNetworkServerPermeateServerMapping)
                .accept(lazyInternalNetworkServerPermeateMappings -> {
                    // 开启映射
                    for (LazyInternalNetworkServerPermeateServerMapping internalNetworkServerPermeateMapping : lazyInternalNetworkServerPermeateMappings) {

                        String permeateTargetIp = internalNetworkServerPermeateMapping.getPermeateTargetIp();
                        Integer permeateTargetPort = internalNetworkServerPermeateMapping.getPermeateTargetPort();
                        Integer visitorPort = internalNetworkServerPermeateMapping.getVisitorPort();
                        Boolean isSsl = internalNetworkServerPermeateMapping.getIsSsl();
                        log.info("init permeate socket ip:{}, port:{},visitorPort:{}", permeateTargetIp, permeateTargetPort, visitorPort);
                        this.createPermeateVisitor(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
                    }
                });

    }

    /**
     * 变更 网络穿透
     *
     * @param permeateTargetIp   客户端目标IP
     * @param permeateTargetPort 客户端莫表端口
     * @param visitorPort        访客端口
     */
    private void changePermeateSocket(String permeateTargetIp, Integer permeateTargetPort, Integer visitorPort, Boolean isSsl) {
        // 删除 客户端映射
        this.closePermeateSocket(visitorPort);
        // 更新 客户端映射
        createPermeateVisitor(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
    }


    /**
     * 删除 通道
     *
     * @param visitorPort 访客端口
     */
    private void closePermeateSocket(Integer visitorPort) {
        // 删除 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyPermeateVisitorContext.getPermeateVisitorSocket(visitorPort);
        if (!ObjectUtils.isEmpty(nettyServerPermeateServerConnectVisitorSocket)) {
            // 关闭端口
            try {
                nettyServerPermeateServerConnectVisitorSocket.close();
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 创建访客
     *
     * @param permeateTargetIp   客户端目标IP
     * @param permeateTargetPort 客户端目标端口
     * @param visitorPort        访客端口
     */
    private void createPermeateVisitor(String permeateTargetIp, Integer permeateTargetPort, Integer visitorPort, Boolean isSsl) {
        // 更新 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyServerPermeateServerConnectVisitorSocket.NettyPermeateVisitorSocketBuilder
                .builder()
                .builderClientTargetIp(permeateTargetIp)
                .builderClientTargetPort(permeateTargetPort)
                .builderVisitorPort(visitorPort)
                .builderIsSsl(isSsl)
                .builderChannelFlowAdapter(channelFlowAdapter)
                .build();
        try {
            nettyServerPermeateServerConnectVisitorSocket.start();
        } catch (Exception e) {
            log.error("内网渗透,网络端口:{},开放失败", visitorPort);
            throw new RuntimeException(e);
        }
    }

}